package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FFNoSuchTableException;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.param.FFTableMapperParam;
import com.fivefu.core.pojo.FfSql;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/12
 */
@Component
public class TableNameComponent implements  SqlHandler {

    @Override
    public void dealSql(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
            /*
               logger
            */

        List<String> unProcessList = ffSql.getUnProcessedTableNameList();
        for (Map.Entry<String, Object> item : jsonObject.entrySet()) {
            //把未处理的表名拿进去
            if (item.getValue() instanceof JSONObject) {
                JSONObject table = (JSONObject) (item.getValue());
                //这里虚不需要加判断？

                unProcessList.add(FFTableMapperParam.getOriginTableName(item.getKey()));//添加原表名
            }
        }
        //映射 暂时不做
        String tableName = "";
        //
        if (unProcessList.size() == 0) {
            throw new FFNoSuchTableException("表的数量不能为0");
        }
        if (unProcessList.size() > 3) {
            throw new FFNoSuchTableException("表的数量不能大于3");
        }
        if (unProcessList.size() == 1) {
            //单表查询
            tableName = unProcessList.get(0);
            ffSql.setTablename(FFTableMapperParam.getOriginTableName(tableName));//根据映射表获取原表名
        }

    }

    @Override
    public int order() {
        return 0;
    }

    private String errorMsg;

    @Override
    public String getErrMsg() {
        return this.errorMsg;
    }

    protected void setErrorMsg(String msg){
        this.errorMsg = msg;
    }
}
